package com.xxtx.trade.thread;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import com.xxtx.trade.agent.mapper.TradeSysAgentMapper;
import com.xxtx.trade.common.enums.ExportEnum;
import com.xxtx.trade.common.util.springUtil.SpringUtil;
import com.xxtx.trade.fieldManage.dto.FieldManageDto;
import com.xxtx.trade.fieldManage.mapper.FieldManageMapper;
import com.xxtx.trade.sysUser.bean.UrlInfos;
import com.xxtx.trade.sysUser.bean.UrlInfosTencent;
import com.xxtx.trade.sysUser.dto.TencentInfoDto;
import com.xxtx.trade.sysUser.dto.TradeSysRoleDto;
import com.xxtx.trade.sysUser.service.TradeSysUserService;
import lombok.Data;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
@Data
public class DownloadTencentInfoThread implements Runnable{
    // 开启多线程用于导出腾讯数据

    private static final Logger LOGGER = LoggerFactory.getLogger(DownloadAdminSimThread.class);
    private TradeSysRoleDto tradeSysRoleDto;

    private int count;
    private String url;
    private String id; // 每次下载时随机出的 id

    private String userId; // 用户id
    private String agentId; // 这个可以用来在info表中查询

    private String role_id; // 用户角色，管理员与普通用户
    private int type; //1

    private TencentInfoDto tencentInfoDto;

    @Override
    public void run() {
        Integer pageCount = count / 100000 + 1;
        TradeSysAgentMapper tradeSysAgentMapper = SpringUtil.getBean(TradeSysAgentMapper.class);
        FieldManageMapper fieldManageMapper = SpringUtil.getBean(FieldManageMapper.class);

        Map<String, Object> hashMap = new HashMap<>();

        Workbook workbook = null;

        ExportParams params = new ExportParams();

        try {
            if (type == 1) {
                List<UrlInfosTencent> users = null;
                TencentInfoDto t_dto = new TencentInfoDto();
                t_dto.copyFrom(this.tencentInfoDto);

                // TODO:查询出全部电话号码


//         查询测试 页数  每次查询10w条数据
                for (int i = 1; i <= pageCount; i++) {

                    t_dto.setPageNo((i - 1) * 100000);
                    if (i == pageCount) {
                        t_dto.setPerPageNum(count % 100000);
                    } else {
                        t_dto.setPerPageNum(100000);
                    }

                    // 获取数据
                    users = tradeSysAgentMapper.selectExcelUrlInfosTencent(t_dto);

                    if (this.role_id.equals("2")) {
                        //通过 EasyPoi 的大数据导出方法 导出
//                        workbook = ExcelExportUtil.exportBigExcel(params, UrlInfos.class, users);
                        workbook = ExcelExportUtil.exportBigExcel(params, UrlInfosTencent.class, users);
                        users.clear();
                    } else {
                        // 生成要导出的数据
                        List<Map<String, String>> resultList = new ArrayList<>();
                        // 生成导出的列名
                        List<ExcelExportEntity> entityList = new ArrayList<>();

                        ExcelExportEntity agentNameEntity = new ExcelExportEntity("客户名称", "agentName");
                        entityList.add(agentNameEntity);

                        // 查询可显示字段，创建列名
                        List<FieldManageDto> fieldManageDtos = fieldManageMapper.getList();
                        for (FieldManageDto fieldManageDto : fieldManageDtos) {
                            if (fieldManageDto.getStatus().equals("1")) {
                                if (fieldManageDto.getSource().equals("3")){
                                    ExcelExportEntity ele = new ExcelExportEntity(fieldManageDto.getName(), fieldManageDto.getName());
                                    entityList.add(ele);
                                }
                            }
                        }
                        // 装载数据
                        for (UrlInfosTencent urlInfosTencent: users){
                            Map<String, String> rowMap = new HashMap<>();
                            for (ExcelExportEntity excelExportEntity: entityList){
                                if (excelExportEntity.getKey().equals("agentName")){
                                    rowMap.put("agentName", urlInfosTencent.getAgentName());
                                }
                                if (excelExportEntity.getKey().equals("urlName")){
                                    rowMap.put("urlName", urlInfosTencent.getUrlName());
                                }
                                if(excelExportEntity.getKey().equals("muid")){
                                    rowMap.put("muid", urlInfosTencent.getMuid());
                                }
                                if (excelExportEntity.getKey().equals("clickTime")){
                                    rowMap.put("clickTime", urlInfosTencent.getClickTime());
                                }
                                if(excelExportEntity.getKey().equals("advertiserId")){
                                    rowMap.put("advertiserId", urlInfosTencent.getAdvertiserId());
                                }
                                if (excelExportEntity.getKey().equals("androidId")){
                                    rowMap.put("androidId", urlInfosTencent.getAndroidId());
                                }
                                if(excelExportEntity.getKey().equals("userAgent")){
                                    rowMap.put("userAgent", urlInfosTencent.getUserAgent());
                                }
                                if (excelExportEntity.getKey().equals("campaignId")){
                                    rowMap.put("campaignId", urlInfosTencent.getCampaignId());
                                }
                                if (excelExportEntity.getKey().equals("agentId")){
                                    rowMap.put("agentId", urlInfosTencent.getAgentId());
                                }
                                if (excelExportEntity.getKey().equals("siteSet")){
                                    rowMap.put("siteSet", urlInfosTencent.getSiteSet());
                                }
                                if (excelExportEntity.getKey().equals("oaid")){
                                    rowMap.put("oaid", urlInfosTencent.getOaid());
                                }
                                if (excelExportEntity.getKey().equals("createTime")){
                                    rowMap.put("createTime", urlInfosTencent.getCreateTime());
                                }
                            }
                            resultList.add(rowMap);
                        }
                        workbook = ExcelExportUtil.exportBigExcel(params, entityList, resultList);
                        resultList.clear();
                        users.clear();
                    }
                }  // 分页写入workbook结束
            }
//            workbook.write(new FileOutputStream("E:/download/" + url));
            workbook.write(new FileOutputStream("/root/develop/export/" + url));

            workbook.close();
            hashMap.put("state", ExportEnum.SUCCESS.getCode());

        } catch (IOException e) {
            e.printStackTrace();
            LOGGER.debug("导出失败信息为" + e.getMessage());
            LOGGER.debug("导出失败信息为" + e.getLocalizedMessage());
            hashMap.put("state", ExportEnum.FAIL.getCode());
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        hashMap.put("id", id);
        Date date = new Date();
        SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String LgTime = sdformat.format(date);
        hashMap.put("endTime", LgTime);
        tradeSysAgentMapper.updateExporeByid(hashMap);

    }


}
